package com.atguigu.gmall.mq.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author wk
 * @create 2021-09-13 20:37
 * 处理死信的配置类
 */
@Component
@Configuration
public class DeadLetterConfig {
    public static final String exchange_dead = "exchange.dead";
    public static final String routing_dead_1 = "routing.dead.1";
    public static final String routing_dead_2 = "routing.dead.2";
    public static final String queue_dead_1 = "queue.dead.1";
    public static final String queue_dead_2 = "queue.dead.2";

    // 私信交换机
    @Bean
    public Exchange deadLetterExchange() {
        return ExchangeBuilder.directExchange(exchange_dead).build();
    }

    // 普通队列
    @Bean
    public Queue queue() {
        return QueueBuilder.durable(queue_dead_2).build();
    }

    // 死信队列
    @Bean
    public Queue deadLetterQueue() {
        Map<String, Object> arguments = new HashMap<>();
        // 配置过期时间 单位毫秒
        arguments.put("x-message-ttl", 10000);
        // 对于死信队列需要配置死信交换机和路由key
        arguments.put("x-dead-letter-exchange", exchange_dead);
        // 配置死信路由
        arguments.put("x-dead-letter-routing-key", routing_dead_2);

        return QueueBuilder.durable(queue_dead_1).withArguments(arguments).build();
    }

    // 队列和交换机进行绑定
    @Bean
    public Binding bindingDeadQueueToDeadLetterExchange(@Qualifier(value = "deadLetterQueue") Queue queue) {
        return BindingBuilder.bind(queue).to(deadLetterExchange()).with(routing_dead_2).noargs();
    }

    @Bean
    public Binding bindingQueueToDeadLetterExchange(@Qualifier(value = "queue") Queue queue) {
        return BindingBuilder.bind(queue).to(deadLetterExchange()).with(routing_dead_1).noargs();
    }
}
